//
//  Render.cpp
//  RenderV1
//
//  Created by 黄翔 on 2019/10/20.
//  Copyright © 2019 黄翔. All rights reserved.
//

#include "Render.h"
#include "render_v1.h"

hxe::Render::Render(std::vector<Material*>* materials):Component("Render")
{
    this->materials = materials;
}

hxe::Render::~Render()
{
    for (unsigned int i = 0; i < materials->size(); i++)
    {
        (*materials)[i]->drop();
    }
    delete materials;
}

void hxe::Render::draw()
{
    Matrix4x4 modelTrans = gameObject->transform->getMatrix();

    Camera* camera = Camera::current;
    Vector3 viewPos = camera->gameObject->transform->position;
    Matrix4x4 viewProjTrans = camera->getViewProjectionMatrix();

    Light* light = SceneInst->getLight();

    MeshFilter* meshFilter = (MeshFilter*)gameObject->getComponent("MeshFilter");
    for (unsigned int i = 0; i < meshFilter->getMeshes()->size(); i++)
    {
        Material* m = (*materials)[i];
        m->prepareDraw();

        Shader* shader = m->getShader();
        shader->setMatrix("modelTrans", modelTrans);
        shader->setVector3("viewPos", viewPos);
        shader->setMatrix("viewProjTrans", viewProjTrans);
        shader->setVector3("lightDirection", light->gameObject->transform->forward);
        shader->setVector4("lightColor", light->lightColor);
        shader->setVector4("ambientColor", light->ambientColor);

        glBindVertexArray((*meshFilter->getMeshes())[i]->vao);
        glDrawElements(GL_TRIANGLES, (int)((*meshFilter->getMeshes())[i]->indices->size()), GL_UNSIGNED_INT, 0);
    }
}

hxe::Material* hxe::Render::getMaterial() const
{
    if (materials->size() == 0)
    {
        return nullptr;
    }

    return (*materials)[0];
}
